<?php

namespace yifang\route\dispatch;

use yifang\lib\Request;
use yifang\route\Rule;
use yifang\exception\HttpException;

class Url extends Controller
{

    public function __construct(Request $request, Rule $rule, $dispatch)
    {
        $this->request = $request;
        $this->rule    = $rule;
        // 解析默认的URL规则
        $dispatch = $this->parseUrl($dispatch);
        parent::__construct($request, $rule, $dispatch, $this->param);
    }

    /**
     * 解析URL地址
     */
    protected function parseUrl($url)
    {
        $depr = $this->rule->config('pathinfo_depr');
        $path = $this->rule->parseUrlPath($url);
        if (empty($path)) {
            return [null, null];
        }
        // 解析控制器
        $controller = !empty($path) ? array_shift($path) : null;
        if ($controller && !preg_match('/^[A-Za-z0-9][\w|\.]*$/', $controller)) {
            throw new HttpException(404,'controller not exists:' . $controller);
        }
        // 解析操作
        $action = !empty($path) ? array_shift($path) : null;
        $var    = [];
        // 设置当前请求的参数
        $this->param = $var;
        // 封装路由
        $route = [$controller, $action];
        if ($this->hasDefinedRoute($route)) {
            throw new HttpException(404,'invalid request:' . str_replace('|', $depr, $url));
        }
        return $route;
    }

    /**
     * 检查URL是否已经定义过路由
     * @access protected
     * @param  array $route 路由信息
     * @return bool
     */
    protected function hasDefinedRoute(array $route)
    {
        list($controller, $action) = $route;
        // 检查地址是否被定义过路由
        $name = strtolower($controller . '/' . $action);
        $host   = $this->request->host(true);
        $method = $this->request->method();
        if ($this->rule->getRouter()->getName($name, $host, $method)) {
            return true;
        }
        return false;
    }
}